<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CloudFiles
 *
 * @author kevinthant
 */
namespace Backuper\Services;
use Backuper\Settings\Rackspace;

class CloudFiles {
    //put your code here
    private static $_instance = null;
    
    private $_objectstore;
    private function __construct() {
       
         // establish our credentials
        $conn = new \OpenCloud\Rackspace(Rackspace::getInstance()->authUrl,
                array('username' => Rackspace::getInstance()->username,
                           'apiKey' => Rackspace::getInstance()->apikey));
        
          // create a Cloud Files (ObjectStore) connection
        $ostore = $conn->ObjectStore(Rackspace::getInstance()->objectstore['name'], Rackspace::getInstance()->objectstore['region']);

        //setDebug(TRUE);

        // set the temp URL secret
        $ostore->SetTempUrlSecret('HelloWorld is awesome');

        // next, make a container named CONTAINER_NAME
        $this->_objectstore = $ostore;
        
       
    }
    
    public function store($containerName, $filename, $metaData = array()){
        
        //$objects = $this->_getObjectList();
        $container = $this->_objectstore->Container($containerName);
        $metaData = \Backuper\Util::mergeOptions(array('name' => basename($filename)), $metaData);
        $obj = $container->DataObject();
        $obj->Create($metaData, $filename);
        
        /*
        if(in_array($name, $objects)){
            //update
            $obj = $this->_container->DataObject(basename($filename));
            $metaData = \Backuper\Util::mergeOptions(array('name' => basename($filename)), $metaData);
            $obj->Update($metaData, $filename);
        }
        else{
            //create 
            
            $metaData = \Backuper\Util::mergeOptions(array('name' => basename($filename)), $metaData);
            $obj = $this->_container->DataObject();
            $obj->Create($metaData, $filename);
        }*/
    }
    
    private function _getObjectList(){
        
        $temp = array();
        $objects = $this->_container->ObjectList(array('format' => 'json'));

        while($obj = $objects->Next()){
          $temp[] = $obj->name;  
        }

        return $temp;
    }
    
    public static function getInstance(){
        
        if(self::$_instance == null){
            self::$_instance = new CloudFiles();
        }
        return self::$_instance;
    }
}

